package com.xy.service;

import com.xy.config.ImgUploadConfig;
import com.xy.util.ImageOperateUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.im4java.core.IM4JavaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by XiuYang on 2016/11/21.
 */
@Service
public class UploadServiceImpl implements UploadService{

    private static final Logger logger = LogManager.getLogger(UploadServiceImpl.class);

    @Autowired
    private ImgUploadConfig imgUploadConfig;

    @Autowired
    private FastDFSService fastDFSService;

    @Override
    public String upload(InputStream inputStream,int imgType,String fileName)throws IOException  {
        String extension = FilenameUtils.getExtension(fileName);
        //保存临时文件
        File tmpFile = saveTmpFile(inputStream,extension);

        //上传原图
        String relativePath = fastDFSService.upload(tmpFile);

        logger.debug(()->"upload master file path:"+relativePath);
        if(StringUtils.isEmpty(relativePath)){
            logger.error("upload master file fail fileName:"+fileName);
            return "";
        }
        //上传小图
        imgUploadConfig.getImgConfig(imgType).forEach((s, imgSize) -> {
            String prefixName = "_"+s;
            String slaveFileTmpName = new StringBuffer(tmpFile.getAbsolutePath().substring(0,tmpFile.getAbsolutePath().indexOf("."))).append(prefixName).append(".").append(extension).toString();
            File slaveFile = null;
            try {
                ImageOperateUtil.zoom(tmpFile.getAbsolutePath(),slaveFileTmpName,imgSize.getWidth(),imgSize.getHeight());
                //裁剪、缩放并上传
                slaveFile = new File(slaveFileTmpName);
                String slaveFilePath = fastDFSService.uploadSlaveFile(relativePath,slaveFile,prefixName,extension);

                logger.debug(()->"slave file path: "+slaveFilePath);
                if(StringUtils.isEmpty(slaveFilePath)){
                    logger.error("upload slave file fail,master file path:"+relativePath);
                }
            } catch (IOException e) {
                logger.error("upload slave image error:{}",e);
                e.printStackTrace();
            } catch (InterruptedException e) {
                logger.error("zoom image error {}",e);
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }finally {
                //删除临时小文件
                FileUtils.deleteQuietly(slaveFile);
            }
        });
        //删除临时文件
        FileUtils.deleteQuietly(tmpFile);
        return relativePath;
    }

    /**
     * 保存临时文件
     * @param inputStream
     * @return
     */
    public File saveTmpFile(InputStream inputStream,String extension) throws IOException{
        String tmpName =  System.currentTimeMillis() + "_" + (int)(100*Math.random()) + "_"+ Thread.currentThread().getId()+"."+extension;
        File tmpDir = new File(imgUploadConfig.getTmpFilePath());
        if (!tmpDir.exists()) {
            tmpDir.mkdirs();
        }
        File tmpFile = new File(tmpDir, tmpName);
        FileUtils.copyInputStreamToFile(inputStream,tmpFile);
        if(tmpFile!=null){
            logger.debug(()->"save temp file success , temp file name:"+tmpName);
        }
        return tmpFile;
    }


}
